matplotlib의 여러가지 플롯

matplotlib는 기본적인 라인 프롯 이외에도 다양한 챠트/플롯 유형을 지원한다.

바 차트

x, y 데이터 중 하나가 카테고리 값인 경우에는 bar 명령과 barh 명령으로 바 차트(bar chart) 시각화를 할 수 있다. 가로 방향으로 바 차트를 그리려면 barh 명령을 사용한다.

자세한 내용은 다음 웹사이트를 참조한다.

바 차트 작성시 주의점은 첫번째 인수인 left 가 x축에서 바(bar)의 왼쪽 변의 위치를 나타낸다는 점이다. 바의 위치를 xtick 위치의 중앙으로 옮기려면 align='center' 인수를 지정해야 한다.


In [2]:
y = [2, 3, 1]
x = np.arange(len(y))
xlabel = ['A', 'B', 'C']
plt.bar(x, y, align='center')
plt.xticks(x, xlabel);


xerr 인수나 yerr 인수를 지정하면 에러 바(error bar)를 추가할 수 있다.


In [3]:
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

plt.barh(y_pos, performance, xerr=error, align='center', alpha=0.4)
plt.yticks(y_pos, people)
plt.xlabel('Performance');


두 개 이상의 바 차트를 한번에 그리는 경우도 있다.


In [4]:
n_groups = 5
means_men = (20, 35, 30, 35, 27)
std_men = (2, 3, 4, 1, 2)
means_women = (25, 32, 34, 20, 25)
std_women = (3, 5, 2, 3, 3)

fig, ax = plt.subplots()

index = np.arange(n_groups)
bar_width = 0.35

opacity = 0.4
error_config = {'ecolor': '0.3'}

rects1 = plt.bar(index, means_men, bar_width,
                 alpha=opacity,
                 color='b',
                 yerr=std_men,
                 error_kw=error_config,
                 label='Men')

rects2 = plt.bar(index + bar_width, means_women, bar_width,
                 alpha=opacity,
                 color='r',
                 yerr=std_women,
                 error_kw=error_config,
                 label='Women')

plt.xlabel('Group')
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(index + bar_width, ('A', 'B', 'C', 'D', 'E'))
plt.legend()

plt.tight_layout()


또는 bottom 인수로 바의 위치를 조정하여 겹친 바 차트(stacked bar chart)도 그릴 수 있다.


In [5]:
N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, menMeans, width, color='r', yerr=menStd)
p2 = plt.bar(ind, womenMeans, width, color='y',
             bottom=menMeans, yerr=womenStd)

plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind + width/2., ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))


Out[5]:
<matplotlib.legend.Legend at 0x7f3789a75090>

스템 플롯

바 차트와 유사하지만 폭(width)이 없는 스템 플롯(stem plot)도 있다. 주로 이산 확률 함수나 자기상관관계(auto-correlation)를 묘사할 때 사용된다.


In [6]:
x = np.linspace(0.1, 2*np.pi, 10)
markerline, stemlines, baseline = plt.stem(x, np.cos(x), '-.')
plt.setp(markerline, 'markerfacecolor', 'b')
plt.setp(baseline, 'color', 'r', 'linewidth', 2);


파이 차트

카테고리 별 값의 상대적인 비교를 해야 할 때는 pie 명령으로 파이 차트(pie chart)를 그릴 수 있다.


In [7]:
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0, 0.1, 0, 0)
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=90)
plt.axis('equal');


히스토그램

히스토그램을 그리기 위한 hist 명령도 제공한다. hist 명령은 bins 인수로 데이터 집계 구간을 받는다. 또한 반환값으로 데이터 집계 결과를 반환해주므로 이 결과를 다른 코드에서 사용할 수도 있다.


In [8]:
x = np.random.randn(5000)
arrays, bins, patches = plt.hist(x, bins=50, normed=True)



In [9]:
arrays


Out[9]:
array([ 0.00410032,  0.00546709,  0.00136677,  0.00273355,  0.00820064,
        0.00820064,  0.01776805,  0.01230096,  0.03553611,  0.03690288,
        0.04783707,  0.06833866,  0.09567413,  0.11070864,  0.14761152,
        0.20774954,  0.2200505 ,  0.23918533,  0.28292207,  0.32119173,
        0.38816362,  0.34579364,  0.37449588,  0.41413231,  0.3990978 ,
        0.3840633 ,  0.37996298,  0.32392527,  0.33349269,  0.25695338,
        0.28018853,  0.23781855,  0.17221344,  0.17631376,  0.1230096 ,
        0.09840768,  0.06287157,  0.05877125,  0.04236997,  0.02460192,
        0.02733547,  0.02186837,  0.00820064,  0.00410032,  0.00820064,
        0.00683387,  0.00410032,  0.        ,  0.00136677,  0.00136677])

In [10]:
bins


Out[10]:
array([ -3.51572074e+00,  -3.36939070e+00,  -3.22306065e+00,
        -3.07673060e+00,  -2.93040056e+00,  -2.78407051e+00,
        -2.63774047e+00,  -2.49141042e+00,  -2.34508037e+00,
        -2.19875033e+00,  -2.05242028e+00,  -1.90609023e+00,
        -1.75976019e+00,  -1.61343014e+00,  -1.46710010e+00,
        -1.32077005e+00,  -1.17444000e+00,  -1.02810996e+00,
        -8.81779911e-01,  -7.35449865e-01,  -5.89119819e-01,
        -4.42789773e-01,  -2.96459727e-01,  -1.50129681e-01,
        -3.79963456e-03,   1.42530412e-01,   2.88860458e-01,
         4.35190504e-01,   5.81520550e-01,   7.27850596e-01,
         8.74180642e-01,   1.02051069e+00,   1.16684073e+00,
         1.31317078e+00,   1.45950083e+00,   1.60583087e+00,
         1.75216092e+00,   1.89849097e+00,   2.04482101e+00,
         2.19115106e+00,   2.33748110e+00,   2.48381115e+00,
         2.63014120e+00,   2.77647124e+00,   2.92280129e+00,
         3.06913133e+00,   3.21546138e+00,   3.36179143e+00,
         3.50812147e+00,   3.65445152e+00,   3.80078157e+00])

스캐터 플롯

두 개의 데이터 집합, 예를 들면 두 벡터의 상관관계를 살펴보려면 scatter 명령으로 스캐터 플롯을 그린다.


In [11]:
X = np.random.normal(0,1,1024)
Y = np.random.normal(0,1,1024)
plt.scatter(X,Y);



In [12]:
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2 
plt.scatter(x, y, s=area, c=colors, alpha=0.5);


Imshow

지금 까지는 1개 혹은 2개의 1차원 자료에 대한 시각화를 살펴보았다. 이제는 행과 열을 가진 2차원 데이터의 시각화에 대해 알아본다. 예를 들어 화상(image) 데이터는 전형적인 2차원 자료이다.

가장 간단한 2차원 자료 시각화 방법은 imshow 명령을 써서 2차원 자료 자체를 각 위치의 명암으로 표시하는 것이다. 자료의 시각화를 돕기위해 다양한 2차원 인터폴레이션을 지원한다.


In [1]:
from sklearn.datasets import load_digits
digits = load_digits()
X = digits.images[0]
X


Out[1]:
array([[  0.,   0.,   5.,  13.,   9.,   1.,   0.,   0.],
       [  0.,   0.,  13.,  15.,  10.,  15.,   5.,   0.],
       [  0.,   3.,  15.,   2.,   0.,  11.,   8.,   0.],
       [  0.,   4.,  12.,   0.,   0.,   8.,   8.,   0.],
       [  0.,   5.,   8.,   0.,   0.,   9.,   8.,   0.],
       [  0.,   4.,  11.,   0.,   1.,  12.,   7.,   0.],
       [  0.,   2.,  14.,   5.,  10.,  12.,   0.,   0.],
       [  0.,   0.,   6.,  13.,  10.,   0.,   0.,   0.]])

In [2]:
plt.imshow(X, interpolation='nearest');
plt.grid(False)



In [4]:
methods = [None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16',
           'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric',
           'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos']
fig, axes = plt.subplots(3, 6, figsize=(12, 6), subplot_kw={'xticks': [], 'yticks': []})
fig.subplots_adjust(hspace=0.3, wspace=0.05)
for ax, interp_method in zip(axes.flat, methods):
    ax.imshow(X, interpolation=interp_method)
    ax.set_title(interp_method)


컨투어 플롯

2차원 자료를 시각화하는 또다른 방법은 명암이 아닌 등고선(contour)을 사용하는 방법이다. contour 혹은 contourf 명령을 사용한다.


In [16]:
def f(x, y):
    return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 -y ** 2)

n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
XX, YY = np.meshgrid(x, y)
ZZ = f(XX, YY)

In [17]:
plt.contourf(XX, YY, ZZ, alpha=.75, cmap='jet');
plt.contour(XX, YY, ZZ, colors='black', linewidth=.5);


3D 서피스 플롯

입력 변수가 x, y 두 개이고 출력 변수가 z 하나인 경우에는 3차원 자료가 된다. 3차원 플롯은 일반 플롯과 달리 Axes3D라는 3차원 전용 axes를 생성해야 한다.

plot_wireframe, plot_surface 명령을 사용한다.


In [18]:
from mpl_toolkits.mplot3d import Axes3D
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
XX, YY = np.meshgrid(X, Y)
RR = np.sqrt(XX**2 + YY**2)
ZZ = np.sin(RR)

In [19]:
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(XX, YY, ZZ, rstride=1, cstride=1, cmap='hot');